package com.dianrui.operation.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.dianrui.operation.R;
import com.dianrui.operation.event.ScanServer;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.view.bindzxing.activity.BindCaptureActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

public class BindServerActivity extends BaseActivity {
    private static final int PERMISSION_REQUEST_WRITE = 2;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.server_name)
    EditText serverName;
    @BindView(R.id.server_address)
    EditText serverAddress;
    @BindView(R.id.top_right)
    TextView topRight;

    @Override
    public int getContentViewId() {
        return R.layout.bind_server;
    }


    @Override
    public void initView() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        }
        EventBus.getDefault().register(this);
        title.setText("绑定域名");
        if (!StringUtils.isEmpty(SharedUtil.getName())) {
            serverName.setText(SharedUtil.getName());
        }
        if (!StringUtils.isEmpty(SharedUtil.getUrl())) {
            serverAddress.setText(SharedUtil.getUrl());
        }
        topRight.setText("扫码绑定");
        topRight.setVisibility(View.VISIBLE);
        setEditTextInhibitInputSpace(serverName);
        setEditTextInhibitInputSpace(serverAddress);
    }

    @Override
    public void initData() {}


    public static void setEditTextInhibitInputSpace(EditText editText){
        InputFilter filter=new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if(source.equals(" ")){
                    return "";
                }else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**扫码后获取区域名(名称和域名)**/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ScanServer scanServer) {
        serverName.setText(scanServer.name);
        serverAddress.setText(scanServer.url);
    }

    @OnClick({R.id.back, R.id.bind_btn,R.id.top_right,R.id.clear_name_img,R.id.clear_address_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.bind_btn:
                if (StringUtils.isEmpty(serverName.getText().toString())) {
                    ToastUtil.showToast("请您输入要绑定的名称");
                    return;
                }
                if (StringUtils.isEmpty(serverAddress.getText().toString())) {
                    ToastUtil.showToast("请您输入要绑定的域名");
                    return;
                }
                if (!MyUtil.isUrlDigit(serverAddress.getText().toString())) {
                    ToastUtil.showToast("域名格式不正确，请重新输入");
                    return;
                }
                SharedUtil.setUrl(serverAddress.getText().toString().trim());
                SharedUtil.setName(serverName.getText().toString().trim());
                spUtils.put("server_name", serverName.getText().toString().trim());
                spUtils.put("server_url", serverAddress.getText().toString().trim());
                ToastUtil.showToast("绑定成功");
                finish();
                break;

            case R.id.top_right:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(BindServerActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent intent=new Intent(BindServerActivity.this, BindCaptureActivity.class);
                        startActivityForResult(intent,113);
                    } else {
                        ActivityCompat.requestPermissions(BindServerActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    Intent intent=new Intent(BindServerActivity.this, BindCaptureActivity.class);
                    startActivityForResult(intent,113);

                }
                break;

            case R.id.clear_name_img:
               serverName.setText("");
                break;

            case R.id.clear_address_img:
                serverAddress.setText("");
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==113){
            String setname=data.getStringExtra("setname");
            String setaddress=data.getStringExtra("setaddress");
            if (!StringUtils.isEmpty(setname) && !StringUtils.isEmpty(setaddress)) {
                serverName.setText(setname);
                serverAddress.setText(setaddress);
            }
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent=new Intent(BindServerActivity.this, BindCaptureActivity.class);
                    startActivityForResult(intent,113);
                }
                break;

            default:
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
